/* eslint-disable array-callback-return,no-undef,prefer-destructuring */
import React, { Component } from 'react';
import { Modal, message } from 'antd';
import * as commonFunc from './commonFunc';
import * as commonBusiness from './commonBusiness'; /* 单据业务功能 */
import * as commonUtils from '../../utils/utils'; /* 通用方法 */
import * as commonConfig from '../../utils/config';
import * as commonServices from '../../services/services';

const { confirm } = Modal;

export default (ChildComponent) => {
  return class extends Component {
    constructor(props) {
      super(props);
      this.state = {
      };
    }
    componentWillReceiveProps(nextProps) {
      const {
        formData, currentId, searchSolution, masterData,
      } = nextProps;
      let { slaveColumn } = nextProps;
      if (commonUtils.isEmptyArr(slaveColumn) && formData.length > 0) {
        const sId = currentId !== undefined ? currentId : '';
        /* 数据Id */
        const slaveConfig = formData[0];
        slaveColumn = commonFunc.getHeaderConfig(slaveConfig);
        let filterCondition = [];
        if (commonUtils.isNotEmptyObject(masterData) && !commonUtils.isEmpty(masterData.sSearchSolutionId) && commonUtils.isNotEmptyArr(searchSolution)) {
          const iIndex = searchSolution.findIndex(item => item.sId === masterData.sSearchSolutionId);
          if (iIndex > -1 && !commonUtils.isEmpty(searchSolution[iIndex].sCondition)) {
            filterCondition = JSON.parse(searchSolution[iIndex].sCondition);
          }
        }
        this.handleGetData(slaveConfig, filterCondition);
        this.props.onSaveState({
          masterConfig: slaveConfig, slaveConfig, slaveColumn, sId, pageLoading: false,
        });
      }
    }

    shouldComponentUpdate(nextProps) {
      const { slaveColumn } = nextProps;
      return commonUtils.isNotEmptyArr(slaveColumn);
    }

    /**   获取表数据   */
    handleGetData = (slaveConfig, filterCondition) => {
      this.props.handleGetDataSet({
        name: 'slave', configData: slaveConfig, condition: { pageNum: 1, pageSize: commonConfig.pageSize, bFilter: filterCondition },
      });
    };
    handlePaginationChange = (page) => {
      const { slaveConfig, slaveFilterCondition } = this.props;
      this.props.handleGetDataSet({
        name: 'slave', configData: slaveConfig, condition: { pageNum: page, pageSize: commonConfig.pageSize, bFilter: slaveFilterCondition },
      });
    };
    /*   取消操作  */
    handleCancel = () => {
      /*   待用数据声明   */
      const { slaveConfig } = this.props;
      const onGetDataOk = this.handleGetData;
      const onSaveStateOk = this.props.onSaveState;
      confirm({
        title: '确定要取消',
        onOk() {
          onGetDataOk(slaveConfig);
          onSaveStateOk({ enabled: false });
        },
        onCancel() {
        },
      });
    };
    /**   点击修改按钮操作   */
    handleEdit = () => {
      const { slaveConfig, masterData, searchSolution } = this.props;
      let filterCondition = [];
      if (commonUtils.isNotEmptyObject(masterData) && !commonUtils.isEmpty(masterData.sSearchSolutionId) && commonUtils.isNotEmptyArr(searchSolution)) {
        const iIndex = searchSolution.findIndex(item => item.sId === masterData.sSearchSolutionId);
        if (iIndex > -1 && !commonUtils.isEmpty(searchSolution[iIndex].sCondition)) {
          filterCondition = JSON.parse(searchSolution[iIndex].sCondition);
        }
      }
      this.handleGetData(slaveConfig, filterCondition);
      this.props.onSaveState({ enabled: true });
    };
    /**   点击新增按钮操作   */
    handleAdd = () => {
      const { slaveData } = this.props;
      const newData = {
        handleType: 'add',
        sId: commonUtils.createSid(),
      };
      this.props.onSaveState({
        slaveData: [newData, ...slaveData],
        enabled: true,
      });
    };
    /* 删除 */
    handleDel = () => {
      const onOkDel = this.handleOkDel;
      confirm({
        title: '确定要删除',
        onOk() {
          onOkDel();
        },
        onCancel() {
        },
      });
    };
    handleOkDel = async () => {
      this.props.onDataRowDel('slave');
      setTimeout(() => {
        this.handleValidateSave();
      });
    };
    /**   toolbar校验保存   */
    handleValidateSave = async () => {
      this.form.validateFieldsAndScroll((err) => {
        /*   验证通过与不通过走不同的流程   */
        if (err) { /*   验证失败   */
          /*   直接渲染显示错误提示   */
          for (const key of Object.keys(err)) {
            message.warning(err[key].errors[0].message);
          }
        } else { /*   验证成功   */
          const {
            slaveData, slaveConfig, slaveDelData,
          } = this.props;
          const data = [];
          data.push(commonBusiness.mergeData('slave', slaveConfig.sTbName, slaveData, slaveDelData));
          this.handleSaveData({ data, sClientType: '1' });
        }
      });
    };
    /**   toolbar保存   */
    handleSaveData = async (params) => {
      const {
        token, sModelsId, masterData, slaveConfig, searchSolution,
      } = this.props;
      const returnData = await commonBusiness.saveData({ token, value: params, sModelsId });
      if (commonUtils.isNotEmptyObject(returnData)) {
        this.props.onSaveState({
          enabled: false,
        });
        let filterCondition = [];
        if (commonUtils.isNotEmptyObject(masterData) && !commonUtils.isEmpty(masterData.sSearchSolutionId) && commonUtils.isNotEmptyArr(searchSolution)) {
          const iIndex = searchSolution.findIndex(item => item.sId === masterData.sSearchSolutionId);
          if (iIndex > -1 && !commonUtils.isEmpty(searchSolution[iIndex].sCondition)) {
            filterCondition = JSON.parse(searchSolution[iIndex].sCondition);
          }
        }
        this.handleGetData(slaveConfig, filterCondition);
        commonUtils.clearStoreDropDownData();
        return true;
      } else {
        return false;
      }
    };
    /**   表单回带   */
    handleForm = (form) => {
      this.form = form;
    };
    /* 作废、取消作废的公用函数 */
    handleInvalid = (obj) => {
      const props = { ...this.props, ...this.state, ...obj };
      const onOkInvaild = this.handleOkChangeInvaild;
      confirm({
        title: obj.title,
        onOk() {
          onOkInvaild(props);
        },
        onCancel() {
        },
      });
    };
    /* 切换作废状态 */
    handleOkChangeInvaild = async (props) => {
      props = this.handleOkInvalid(props);
      this.setState({ ...props });
    };
    /** 作废，取消作废 */
    handleOkInvalid = async (props) => {
      const {
        sModelsId, slaveData, slaveConfig, handleType, slaveSelectedRowKeys,
      } = props;
      if (commonUtils.isNotEmptyArr(slaveSelectedRowKeys)) {
        const { token } = props.app;
        const { sTbName } = slaveConfig;
        const value = {
          sClientType: '1',
          sId: slaveSelectedRowKeys,
          sTableName: sTbName,
          handleType,
          sBooleanCheck: false,
        };
        const url = `${commonConfig.server_host}checkModel/updatebInvalid?sModelsId=${sModelsId}`;
        const { data } = await commonServices.postValueService(token, value, url);
        if (data.code === 1) {
          message.success(data.msg);
          for (const key of slaveSelectedRowKeys) {
            const selectData = slaveData.filter(item => item.sId === key);
            selectData.bInvalid = handleType === 'toVoid';
          }
        } else {
          this.props.getServiceError(data);
        }
        return props;
      } else {
        message.warn('请选择作废数据');
      }
    };
    /** 按钮操作事件 */
    handleButtonClick = (name) => {
      if (name === 'BtnOut') {
        this.handleOut();
      } else if (name === 'BtnRefresh') {
        const { slavePagination } = this.props;
        this.handlePaginationChange(slavePagination.current);
      } else if (name === 'BtnSetPeriod') {
        this.handleBtnSetPeriod();
      } else if (name === 'BtnRelievePeriod') {
        this.handleBtnRelievePeriod();
      }
    };
    /* 导出Excel */
    handleOut = () => {
      const { slaveConfig, slaveFilterCondition, sFilterOrderBy } = this.props;
      let url = `${commonConfig.server_host}excel/export/${slaveConfig.sId}?sModelsId=${slaveConfig.sParentId}&token=${this.props.app.token}`;
      if (commonUtils.isNotEmptyArr(slaveFilterCondition)) {
        url = `${url}&bFilter=${encodeURIComponent(JSON.stringify(slaveFilterCondition))}`;
      }
      if (sFilterOrderBy !== undefined && sFilterOrderBy !== '' && Object.keys(sFilterOrderBy).length > 0) {
        url = `${url}&sFilterOrderBy=${encodeURIComponent(JSON.stringify(sFilterOrderBy))}`;
      }
      window.open(url);
    };
    /* 设置期初 */
    handleBtnSetPeriod = async () => {
      const { sTbName } = this.props.masterConfig;
      let sClomunType = '';
      if (sTbName === 'cahsupplyinit') {
        sClomunType = 'bAP';
      } else if (sTbName === 'cahcustomerinit') {
        sClomunType = 'bAR';
      } else if (sTbName === 'cahcashierinit') {
        sClomunType = 'bCashier';
      }
      const { sModelsId } = this.props;
      const { token } = this.props.app;
      const url = `${commonConfig.server_host}sysAccountPeriod/updateSysAccountPeriod?sModelsId=${sModelsId}`;
      const value = { sClientType: '1', handleType: 'add', sClomunType };
      const { data } = await commonServices.postValueService(token, value, url);
      if (data.code === 1) {
        message.success(data.msg);
        this.props.onSaveState({ adDisabled: true });
      } else {
        this.props.getServiceError(data);
      }
    };
    /* 解除锁定 */
    handleBtnRelievePeriod = async () => {
      const { sModelsId } = this.props;
      const { token } = this.props.app;
      const { sTbName } = this.props.masterConfig;
      let sClomunType = '';
      if (sTbName === 'cahsupplyinit') {
        sClomunType = 'bAP';
      } else if (sTbName === 'cahcustomerinit') {
        sClomunType = 'bAR';
      } else if (sTbName === 'cahcashierinit') {
        sClomunType = 'bCashier';
      }
      const url = `${commonConfig.server_host}sysAccountPeriod/updateSysAccountPeriod?sModelsId=${sModelsId}`;
      const value = { sClientType: '1', handleType: 'reset', sClomunType };
      const { data } = await commonServices.postValueService(token, value, url);
      if (data.code === 1) {
        message.success(data.msg);
        this.props.onSaveState({ adDisabled: false });
      } else {
        this.props.getServiceError(data);
      }
    };
    render() {
      return (
        <ChildComponent
          {...this.props}
          {...this.state}
          onCancel={this.handleCancel}
          onAdd={this.handleAdd}
          onEdit={this.handleEdit}
          onDel={this.handleDel}
          onSubmit={this.handleValidateSave}
          onReturnForm={this.handleForm}
          onPaginationChange={this.handlePaginationChange}
          onGetData={this.handleGetData}
          onButtonClick={this.handleButtonClick}
          onChangeInvalid={this.handleInvalid}
        />
      );
    }
  };
};
